import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper/api/wallhaven.dart';
import 'package:wallpaper/components/images/image_list.dart';
import 'package:wallpaper/model/image_base.dart';

class WallhavenList extends StatefulWidget {
  final String q;
  final String type;
  final bool change;
  final String ratio;
  final String order;
  final String purity;
  final String categories;
  final String customize;

  const WallhavenList({
    super.key,
    required this.q,
    required this.type,
    required this.change,
    this.ratio = '',
    this.order = 'desc',
    this.purity = '100',
    this.categories = '111',
    this.customize = '110',
  });

  @override
  State<WallhavenList> createState() => _WallhavenPageState();
}

class _WallhavenPageState extends State<WallhavenList>
    with TickerProviderStateMixin {
  String data = 'data';
  int page = 1;
  List imageList = [];
  bool isLoading = false;

  Future<void> getWallhaven() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    final prefs = await SharedPreferences.getInstance();
    String apiKey = prefs.getString('wallhaven_apikey') ?? '';
    try {
      Response res = await wallhavenSearch(
        q: widget.q,
        page: page,
        type: widget.type,
        apikey: apiKey,
        ratio: widget.ratio,
        order: widget.order,
        purity: widget.purity,
        categories: widget.categories,
      );
      List imgs = res.data['data'];

      for (var img in imgs) {
        setState(() {
          imageList.add(
            ImageBase(
              largePath: img['path'],
              smallPath: img['thumbs']['original'],
              tags: (img['tags'] as List<dynamic>?)?.join(' ') ?? '',
              width: img['dimension_x'] ?? 1,
              height: img['dimension_y'] ?? 1.7,
            ),
          );
        });
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  bool isPC(String radio) {
    try {
      List<double> ratios =
          radio.split('x').map((e) => double.tryParse(e) ?? 0).toList();
      if (ratios.length != 2) return false;
      if (ratios[0] >= ratios[1]) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }

  @override
  void initState() {
    super.initState();
    getWallhaven();
  }

  // 监听 change 变化
  @override
  void didUpdateWidget(covariant WallhavenList oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.change != widget.change) {
      setState(() {
        imageList = [];
        page = 1;
      });
      getWallhaven();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ImageList(
      imageList: imageList,
      isLoading: isLoading,
      isPC: isPC(widget.ratio),
      isWaterfallFlow: true,
      onImageBottomLoading: () {
        setState(() {
          page++;
        });
        getWallhaven();
      },
      onImageListRefresh: () {
        setState(() {
          imageList = [];
          page = 1;
        });
        getWallhaven();
      },
    );
  }
}
